<?php

use \Nette\Application as NA,
	\Nette\Security as NS;

/**
 * Sign in/out presenters.
 *
 * @author	 Jan Voráček
 * @package	Tasker
 */
class SignPresenter extends BasePresenter
{

	protected function startup()
	{
		parent::startup();
		self::$mustLogin = false;
	}

	protected function beforeRender()
	{
		parent::beforeRender();
		if ($this->getUser()->isLoggedIn())
		{
			$this->redirect('NoticeBoard:default');
		}
	}

	/**
	 * Sign in form component factory.
	 * @return Nette\Application\AppForm
	 */
	protected function createComponentSignInForm()
	{
		$form = new NA\UI\Form;
		$form->addText('username', 'Jméno:')
				->setRequired('Prosím zadejte jméno');

		$form->addPassword('password', 'Heslo:')
				->setRequired('Prosím zadejte heslo');

		$form->addSubmit('send', 'Přihlásit');

		$form->onSuccess[] = callback($this, 'signInFormSubmitted');
		return $form;
	}

	public function signInFormSubmitted($form)
	{
		try
		{
			$values = $form->getValues();
			$this->getUser()->setExpiration('+ 20 minutes', TRUE);
			$this->getUser()->login($values->username, $values->password);

			$this->redirect('NoticeBoard:');
		} catch (NS\AuthenticationException $e)
		{
			$form->addError($e->getMessage());
		}
	}

	public function actionOut()
	{
		$this->getUser()->logout(true);
		$this->flashMessage('You have been signed out.');
		$this->redirect('in');
	}

}
